import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/layout'
import store from '@/store'


Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'index',
        component: Layout,
        redirect: '/home',
        children: [
            {
                path: '/home',
                name: 'home',
                component: () => import('@/views/home/index.vue'),
                meta: {icon: 'el-icon-s-home', title: '首页'}
            },
            {
                path: '/userCenter',
                name: 'userCenter',
                component: () => import('@/views/system/center/index.vue'),
                hidden: true
            },
        ]
    },
    {
        path: '/login',
        name: 'login',
        component: Login
    },
    {
        path: '/404',
        component: () => import('@/views/error/404.vue'),
        hidden: true
    },
    {
        path: '/bigdataplan',
        name: 'bigdataplan',
        component: () => import('@/views/bigdata/plan.vue'),
        hidden: true
    },

]

const router = new VueRouter({
    mode: "history",
    routes
})


const whiteList = ['/login']


// 导航守卫，渲染动态路由
router.beforeEach((to, from, next) => {
    // console.log(to.path,from.path)
    let token = localStorage.getItem('token')
    if (token) { // 判断是否有token
        if (to.path === '/login') {
            next({path: '/'});
        } else {
            if (store.getters.userInfo.username == null) { // 判断当前用户是否已拉取完user_info信息
                store.dispatch('GetInfo').then(() => { // 拉取info
                    store.dispatch('GetRoutes').then(res => {
                        generateRoutes(res.data)
                        router.addRoutes(routes)
                        generateMenus(res.data)
                        next({...to, replace: true}) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                    }).catch(err => {
                        console.log(err);
                        next('/login');
                    });
                });
            }
            next() //当有用户权限的时候，说明所有可访问路由已生成 如访问没权限的全面会自动进入404页面
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
            next();
        } else {
            next('/login'); // 否则全部重定向到登录页
        }
    }
});
router.afterEach(() => {

})

// 生成菜单列表
function generateMenus(userRoutes) {
    // 将生成好的菜单列表存到vuex
    // store.commit('SET_USERROUTES', newRoute)
    // console.log(userRoutes)
    let menus = userRoutes.filter(item => {
        if (item.children.length === 0) {
            delete item.children

        } else {
            item.children.forEach(chItem => {
                if (chItem.component == null || chItem.path == null || chItem.name == null) {
                    delete item.children
                }
            })
        }
        return item

    })
    store.commit('SET_MENUS', menus)
    console.log(menus)
}

// 过滤生成权限路由
function generateRoutes(userRoutes) {
    let newRoute = []
    userRoutes.forEach(route => {
        if (route.path == null || route.component == null) {
            route.children.forEach(chRoute => {
                newRoute.push({
                    path: chRoute.path,
                    name: chRoute.name,
                    component: () => import(`@/views${chRoute.component}`),
                    hidden: chRoute.hidden,
                    meta: chRoute.meta
                })
            })
        } else {
            newRoute.push({
                path: route.path,
                name: route.name,
                component: () => import(`@/views${route.component}`),
                hidden: route.hidden,
                meta: route.meta
            })
        }
    })
    // routes[0].children = newRoute


    // 将生成好的路由动态加入到路由表中
    routes[0].children.push.apply(routes[0].children, newRoute)
    routes.push({
        path: '*',
        redirect: '/404',
        hidden: true
    })

}


export default router
